package cn.frontop.funswitch.config.web;

import cn.frontop.funswitch.common.Result;
import cn.hutool.core.util.ClassUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 请求后添加请求ID
 * @author Yun
 */
@ControllerAdvice("cn.frontop.funswitch")
public class PostResponseAdvice implements ResponseBodyAdvice<Result<Object>> {


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return ClassUtil.isAssignable(returnType.getParameterType(), Result.class);
    }

    @Override
    public Result<Object> beforeBodyWrite(Result<Object> body,
                                          MethodParameter returnType,
                                          MediaType selectedContentType,
                                          Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                          ServerHttpRequest request,
                                          ServerHttpResponse response) {
        if (body != null){
            body.setRequestId(ServiceContext.getRequestId());
        }
        return body;
    }
}

